import { Card, Spin } from 'antd';
import { Meta } from 'antd/es/list/Item';
import { useEffect, useMemo, useState } from 'react';
import { Web3 } from 'web3';

import { getNFTMetadata } from '../../../../api/services.ts';
import { getTokensByAccount } from '../../../../api/walletsAPI.ts';
import { CommonText } from '../../../../components/typography/CommonText.tsx';
import { convertIpfsToHttp } from '../../utils.ts';

import { useMyNFTSStyles } from './styles.tsx';

import type { MetadataList } from '../../../../types.ts';

export const TabMyNFTs = () => {
    const { styles } = useMyNFTSStyles();
    const [loading, setLoading] = useState(false);
    
    const [NFTs, setNFTs] = useState<MetadataList>([]);
    const [text, setText] = useState('');
    
    useEffect(() => {
        const getNFTsMeta = async () => {
            setLoading(true);
            const web3 = new Web3(window.ethereum);
            const accounts = await web3.eth.getAccounts();

            const account = accounts[0];

            setText('получаем список токенов...');
            const tokens = await getTokensByAccount(account);
            const NFTSMetaData = [];

            let count = 0;

            for (const token of tokens) {
                count++;
                setText(`получаем метадату ${count} токена из ${tokens.length}`);
                const metadata = {
                    img: 'https://storage.yandexcloud.net/picture/error_no_picture.webp',
                    name: 'нет имени',
                    contract: token.tokenContract,
                    checked: false,
                    tokenId: token.tokenID,
                };
                try {
                    const response = await getNFTMetadata(token.tokenURI);

                    metadata.img = convertIpfsToHttp(response.image);
                    metadata.name = response.name;

                } catch (e) { /* empty */ }

                NFTSMetaData.push(metadata);
            }

            setNFTs(NFTSMetaData);
            setLoading(false);
        };
        void getNFTsMeta();

    }, []);
    
    const NFTGrid = useMemo(() => {

        return (
            <div className={styles.cardsWrapper}>
                {NFTs.map((item, index) => (

                    <Card
                        key={item.contract + item.tokenId + index}
                        className={styles.card}
                        cover={<img alt={item.contract} src={item.img}/>}
                        bordered={false}
                    >
                        <Meta title={item.name}/>
                    </Card>

                ))}
            </div>
        );
        
    }, [NFTs, styles]);
    
    return (
        <>
            {loading
                ?  (
                    <>
                        <CommonText>{text}</CommonText>
                        <Spin size="large"/>
                    </>
                )
                : NFTGrid}
        </>
    );
};

